package com.tiancheng.trade.settlement.service.settlement.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancheng.trade.commom.core.data.PageInfo;
import com.tiancheng.trade.settlement.mapper.settlement.ClearBankSummaryCmbMapper;
import com.tiancheng.trade.settlement.model.settlement.ClearBankSummaryCmb;
import com.tiancheng.trade.settlement.service.settlement.IClearBankSummaryCmbService;
import com.tiancheng.trade.settlement.util.ExcelUtil;
import com.tiancheng.trade.settlement.util.ObjectConvertUtil;
import com.tiancheng.trade.settlement.vo.settlement.admin.ClearCmbExportQueryVO;
import com.tiancheng.trade.settlement.vo.settlement.admin.ClearCmbQueryVO;
import com.tiancheng.trade.settlement.vo.settlement.admin.res.ClearCmbExportResVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 清分汇总（招行）
 */
@Service
public class ClearBankSummaryCmbService implements IClearBankSummaryCmbService {

    @Autowired
    ClearBankSummaryCmbMapper clearBankSummaryCmbMapper;

    /**
     * 查询清分汇总
     *
     * @param clearCmbDownloadQueryVo 查询条件
     * @return
     */
    private List<ClearBankSummaryCmb> getClearBankSummaryCmbForExport(ClearCmbExportQueryVO clearCmbDownloadQueryVo) {
        QueryWrapper<ClearBankSummaryCmb> conditions = new QueryWrapper<>();
        conditions.select("clear_batch_no", "clear_date", "mch_id", "clear_amount", "pay_acct", "pay_acct_name", "col_acct", "col_acct_name");
        if (StringUtils.isNotBlank(clearCmbDownloadQueryVo.getBatchDateBegin())) {
            conditions.ge("accounts_file_date", clearCmbDownloadQueryVo.getBatchDateBegin().replace("-", ""));
        }
        if (StringUtils.isNotBlank(clearCmbDownloadQueryVo.getBatchDateEnd())) {
            conditions.lt("accounts_file_date", clearCmbDownloadQueryVo.getBatchDateEnd().replace("-", "") + "235959");
        }
        return clearBankSummaryCmbMapper.selectList(conditions);
    }

    /**
     * 分页查询
     *
     * @param clearCmbQueryVo 查询条件
     * @return
     */
    public PageInfo findPageList(ClearCmbQueryVO clearCmbQueryVo) {
        int page = clearCmbQueryVo.getCurrentPage();
        int limit = clearCmbQueryVo.getPageSize();
        QueryWrapper<ClearBankSummaryCmb> conditions = new QueryWrapper<>();
        if (StringUtils.isNotBlank(clearCmbQueryVo.getClearBatchNo())) {
            conditions.eq("clear_batch_no", clearCmbQueryVo.getClearBatchNo());
        }
        if (StringUtils.isNotBlank(clearCmbQueryVo.getMchId())) {
            conditions.eq("mch_id", clearCmbQueryVo.getMchId());
        }
        if (StringUtils.isNotBlank(clearCmbQueryVo.getPayAcct())) {
            conditions.eq("pay_acct", clearCmbQueryVo.getPayAcct());
        }
        if (StringUtils.isNotBlank(clearCmbQueryVo.getPayAcctName())) {
            conditions.eq("pay_acct_name", clearCmbQueryVo.getPayAcctName());
        }
        if (StringUtils.isNotBlank(clearCmbQueryVo.getColAcct())) {
            conditions.eq("col_acct", clearCmbQueryVo.getColAcct());
        }
        if (StringUtils.isNotBlank(clearCmbQueryVo.getColAcctName())) {
            conditions.eq("col_acct_name", clearCmbQueryVo.getColAcctName());
        }
        if (StringUtils.isNotBlank(clearCmbQueryVo.getClearDateBegin())) {
            conditions.ge("clear_date", clearCmbQueryVo.getClearDateBegin().replace("-", "") + "000000");
        }
        if (StringUtils.isNotBlank(clearCmbQueryVo.getClearDateEnd())) {
            conditions.lt("clear_date", clearCmbQueryVo.getClearDateEnd().replace("-", "") + "235959");
        }
        PageInfo<ClearBankSummaryCmb> pageInfo = clearBankSummaryCmbMapper.find(conditions, page, limit);
        PageInfo<ClearCmbExportResVO> pageInfoRes = new PageInfo<>();
        pageInfoRes.setList(getClearCmbExportResDataForQuery(pageInfo.getList()));
        pageInfoRes.setPagination(pageInfo.getPagination());
        return pageInfoRes;
    }

    /**
     * 导出
     *
     * @param clearCmbDownloadQueryVo 查询条件
     */
    public void export(ClearCmbExportQueryVO clearCmbDownloadQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<ClearBankSummaryCmb> list = getClearBankSummaryCmbForExport(clearCmbDownloadQueryVo);
        List<Map<String, Object>> mapList = listConvert(getClearCmbExportResData(list));
        String fileName = "CmbClearSummary.xlsx";
        String[] title = {"清分批号", "清分执行时间", "商户号", "清分金额", "付款账号", "付款账户名", "收款账号", "收款账户名"};
        Workbook workbook = ExcelUtil.buildWorkbook("招行清分汇总", title, mapList);
        ExcelUtil.exportExcle(request, response, workbook, fileName);
    }

    /**
     * 数据转换
     *
     * @param list
     * @return
     */
    private List<Map<String, Object>> listConvert(List<ClearCmbExportResVO> list) {
        List<Map<String, Object>> list_map = new ArrayList<>();
        try {
            for (ClearCmbExportResVO t : list) {
                Field[] fields = t.getClass().getDeclaredFields();
                Map<String, Object> m = new LinkedHashMap<>();
                for (Field field : fields) {
                    String keyName = field.getName();
                    PropertyDescriptor pd = new PropertyDescriptor(keyName, t.getClass());
                    Method getMethod = pd.getReadMethod();// 获得getter方法
                    Object o = getMethod.invoke(t);// 执行get方法返回一个Object
                    m.put(keyName, o);
                }
                list_map.add(m);
            }
            return list_map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取并转换清分数据(导出)
     *
     * @param list 清分数据
     * @return
     */
    private List<ClearCmbExportResVO> getClearCmbExportResData(List<ClearBankSummaryCmb> list) {
        List<ClearCmbExportResVO> listRes = new ArrayList<>();
        for (ClearBankSummaryCmb summaryCmb : list) {
            ClearCmbExportResVO resVo = ObjectConvertUtil.convert(summaryCmb, ClearCmbExportResVO.class).get();
            BigDecimal clearAmount = new BigDecimal(summaryCmb.getClearAmount());
            resVo.setClearAmount(clearAmount.divide(new BigDecimal(100)).toString());
            resVo.setClearDate(summaryCmb.getClearDate());
            listRes.add(resVo);
        }
        return listRes;
    }

    /**
     * 获取并转换清分数据(分页查询)
     *
     * @param list 清分数据
     * @return
     */
    private List<ClearCmbExportResVO> getClearCmbExportResDataForQuery(List<ClearBankSummaryCmb> list) {
        List<ClearCmbExportResVO> listRes = new ArrayList<>();
        for (ClearBankSummaryCmb summaryCmb : list) {
            ClearCmbExportResVO resVo = ObjectConvertUtil.convert(summaryCmb, ClearCmbExportResVO.class).get();
            resVo.setClearAmount(summaryCmb.getClearAmount().toString());
            resVo.setClearDate(summaryCmb.getClearDate());
            listRes.add(resVo);
        }
        return listRes;
    }

}
